import { createRouter, createWebHashHistory,createWebHistory } from 'vue-router'

const routes = [
  {
    path: '/login',
    name: 'userLogin',
    component: () => import('./views/login/userLogin.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    name: 'appIndex',
    component: () => import('./views/index/appIndex.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/letter',
    name: 'letter',
    component: () => import('./views/index/letter.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/recover',
    name: 'appIndexRecover',
    component: () => import('./views/index/recover.vue'),
    meta: { requiresAuth: true }
  },
]
const router = createRouter({
  history: createWebHistory(),
  // history: createWebHashHistory(import.meta.env.BASE_URL),
  routes,
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  const shop = localStorage.getItem('shop') // 获取用户登录状态
  const requiresAuth = to.matched.some(record => {
    return record.meta.requiresAuth
  }) // 检查目标路由是否需要验证

  if (requiresAuth && !shop) { // 如果目标路由需要验证且用户未登录
    next({
      path: '/login', // 重定向到登录页面
      query: { redirect: to.fullPath } // 将当前路由路径作为查询参数，以便登录后重定向回该页面
    })
  } else {
    next() // 否则，继续导航
  }
})

window.$router = router
Object.defineProperty(window, '$route', {
  get () {
    return router.currentRoute.value
  },
})
export default router
